/*
* @Author: jh
* @Date: 2018/4/10
* @description: 系统 cvs添加
*/
<template>
  <div>
     <el-dialog custom-class="cm-el-dialog" :title="id==='-1'?'添加用户':'编辑用户'" :visible=true center width="45%" :before-close="isShowAddFun" :close-on-click-modal=false :append-to-body=true>
        <el-form :model="form"   ref="form" label-width="100px" :rules='rules'>
            <el-form-item label="客户类型" prop='userType'>
                <el-select v-model="form.userType" placeholder="请选择客户类型" class="el-select-100"  @change="changeUserType">
                  <!-- <el-option label="请选择" value=""></el-option> -->
                  <el-option 
                      v-for='(item,index) in guestType'
                      :key='index' 
                      :label="item.dictName" 
                      :value="item.dictValue">
                    </el-option>
                </el-select>
            </el-form-item>
              <el-form-item label="企业名称" prop='company' v-if="form.userType==='1'">
              <el-input v-model="form.company" auto-complete="off" :maxLength="50" placeholder="请输入企业名称"></el-input>
            </el-form-item>
             <el-form-item label="高校名称"  prop='userName' v-if="form.userType==='3'">
              <el-input v-model="form.userName" auto-complete="off" :maxLength="50" placeholder="请输入高校名称"></el-input>
            </el-form-item>
            <el-form-item label="用户名称"  prop='userName'  v-if="form.userType!=='3'">
              <el-input v-model="form.userName" auto-complete="off" :maxLength="50" placeholder="请输入用户名称"></el-input>
            </el-form-item>
            <el-form-item label="职务" prop='position'>
              <el-input v-model="form.position" auto-complete="off" :maxLength="50" placeholder="请输入职务"></el-input>
            </el-form-item>
            <el-form-item label="登录账号" prop='accountName'>
                <el-input v-model="form.accountName" :maxLength="20" placeholder="请输入登录账号"  :disabled="id!=='-1'"></el-input>
            </el-form-item>
            <!-- 添加 -->
            <el-form-item label="密码" prop='accountPasswd' v-if="id==='-1'">
                <el-input v-model="form.accountPasswd" type="password" :maxLength="20" placeholder="请输入密码"></el-input>
            </el-form-item>
             <el-form-item label="确认密码" prop='accountPasswd2' v-if="id==='-1'">
                <el-input v-model="form.accountPasswd2" type="password" :maxLength="20" placeholder="请再次输入密码"></el-input>
            </el-form-item>
             <!-- 编辑 -->
              <el-form-item label="密码" prop='accountPasswd'  v-if="id !=='-1'" @click.native="changePassConfirm">
                <el-input v-model="form.accountPasswd" type="password" class='ca-pwdDisabled' :disabled="!changePwdFlag"  :maxLength="20" placeholder="请输入密码"></el-input>
            </el-form-item>
             <el-form-item label="确认密码" prop='accountPasswd2'  v-if="id !=='-1'" @click.native="changePassConfirm">
                <el-input v-model="form.accountPasswd2" type="password"  class='ca-pwdDisabled' :disabled="!changePwdFlag" :maxLength="20" placeholder="请再次输入密码"></el-input>
            </el-form-item>
             <el-form-item label="授权到期日" prop='licenseExpireDate'>
                    <el-date-picker
                        v-model="form.licenseExpireDate"
                        class="el-select-100"
                        type="date"
                        placeholder="请选择日期">
                    </el-date-picker>
                </el-form-item>
            <el-form-item label="手机号">
              <el-row>
                <el-col :span="13">
                   <el-form-item prop='areaCode'>
                       <!-- 不显示下拉 时-->
                    <el-select v-model="form.areaCode" placeholder="请选择区号"  @visible-change="showOption" v-if='isOptionShow' class="el-select-100">
                        <el-option 
                          v-for="(item,index) in areaCodeList"
                          :key='index'
                          :label="item.show" 
                          :value="item.areaCode">
                        </el-option>
                    </el-select>   
                    <!-- 显示下拉时 -->
                    <el-select v-model="form.areaCode" placeholder="请选择区号"  @visible-change="showOption" v-else  class="el-select-100">
                         <!-- <el-option label="请选择" value=""></el-option> -->
                        <el-option  
                          v-for="(item,index) in areaCodeList"
                          :key='index'
                          :label="item.areaCode" 
                          :value="item.areaCode">
                        </el-option>
                      </el-select>
                    </el-form-item>
                </el-col> 
                <el-col :span="10" :offset='1'>  
                   <el-form-item prop='mobile'>
                <!-- <el-col> -->
                    <el-input v-model="form.mobile" :maxLength="11" placeholder="请输入11位手机号码"></el-input>
                   </el-form-item>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="邮箱" prop='email' >
                <el-input v-model="form.email" :maxLength="20" placeholder="请输入邮箱"></el-input>
            </el-form-item>
            <el-form-item label="客户状态" prop='licenseStatus'>
                <el-select v-model="form.licenseStatus" placeholder="请选择客户状态" class="el-select-100">
                  <!-- <el-option label="请选择" value=""></el-option> -->
                  <el-option 
                      v-for='(item,index) in guestState'
                      :key='index' 
                      :label="item.dictName" 
                      :value="item.dictValue">
                  </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="ip段" prop='ipLimit' v-if="form.userType==='3'">
                <el-row v-for="(item,index) in ipArr" :key='index'>
                  <el-col :span='21'>
                     <el-input v-model="item.ip" :maxLength="2000" placeholder="请输入ip"></el-input>
                  </el-col>
                  <el-col :span='3'>
                    <button type="button" 
                       v-if='index===0'
                        @click="addRow()"
                        class="custom-btn custom-btn-round m-l-15">
                        <i class="fa fa-plus"></i>
                    </button>
                     <button type="button" 
                        v-else
                        @click="removeRow(index)"
                        class="custom-btn custom-btn-round m-l-15">
                        <i class="fa fa-remove"></i>
                    </button>
                  </el-col>
                </el-row>
            </el-form-item>
            <el-form-item label="备注" prop='remark'>
                <el-input v-model="form.remark" type="textarea" :maxLength="2000"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" >
            <el-button @click="isShowAddFun" round>取 消</el-button>
            <el-button type="primary" @click="validationField('form')" round>提交</el-button>
            <!-- <el-button type="primary" @click="addCvsUser" round>提交</el-button> -->
        </div>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import Vue from 'vue';
import { Component, Watch, Prop } from 'vue-property-decorator';
import CvsUserService from '../../../service/cvs/cvs-user';
import { CvsUserDTO } from '../../../api/Interface';

interface CvsUserInfo extends CvsUserDTO {
  accountPasswd2: string;
}
interface Rules {
      ipLimit: Array<object>;
      userType: Array<object>;
      company: Array<object>;
      userName: Array<object>;
      position: Array<object>;
      accountName: Array<object>;
      accountPasswd: Array<object>;
      accountPasswd2: Array<object>;
      licenseExpireDate: Array<object>;
      areaCode: Array<object>;
      mobile: Array<object>;
      email: Array<object>;
      licenseStatus: Array<object>;
}
@Component({
  components: { }
})
export default class CompanyList extends Vue {
  // 初始化数据 相当于data
  public msg: number = 123;
  public form: CvsUserInfo = { areaCode: '86' } as CvsUserInfo; 
  public modifierId: string = '1'; // 其他参数
  public createrId: string = '1'; // 其他参数
  public status: number = 0; // 其他参数
  public ipArr: object[] = [{ ip: ''}]; // ip数组
  public guestState:  Array< object > = this.$store.state.user.dictionary.dicList.guestState; // 客户状态
  public guestType:  Array< object > = this.$store.state.user.dictionary.dicList.guestType; // 客户类型
  public areaCodeList: Array< object > = this.$store.state.user.dictionary.areaCodeList; // 区号
  public changePwdFlag: boolean = false; // 是否修改密码
  public isOptionShow: boolean = false; // 是否显示下拉
  public logoId: string = this.$store.state.user.uid; // 当前登陆者的id
  public rules: Rules = {
      ipLimit: [
            { validator: this.validateIp, trigger: 'blur', required: true },
      ],
      userType: [
              { required: true, message: '请输入用户名称', trigger: 'change' },
      ],
      company: [
              { required: true, message: '请选择用户角色', trigger: 'change' },
      ],
      userName: [
              { required: true, message: '请输入登录账号', trigger: 'blur' }, 
      ],
      position: [
              { required: true, message: '请输入职务', trigger: 'change' },
      ],
      accountName: [
              { required: true, message: '请选择用户角色', trigger: 'change' },
      ],
      accountPasswd: [
              { required: true, validator: this.validatePass, trigger: 'blur' },
      ],
      accountPasswd2: [
              {required: true, validator: this.validatePass2, trigger: 'blur' },
      ],
      licenseExpireDate: [
              { required: true, message: '请选择时间', trigger: 'change' },
      ],
      areaCode: [],
      mobile: [
               {required: false, validator: this.validatePhone, trigger: 'blur' },
      ],
      email: [
               { required: true, message: '请输入邮箱地址', trigger: 'blur' },
               { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ],
      licenseStatus: [
              { required: true, message: '请输入客户状态', trigger: 'change' },
      ],
  };
  // refs
  public $refs: {
     form: HTMLFormElement
   };
  @Prop()
  public isShowAddFun: () => void;
  @Prop({default: '-1'})
  public id: string;
  // watch
  @Watch('msg')
  public onChildChanged(val: string, oldVal: string) {
    return val + '***';
  }

  // 声明周期钩子
  public mounted() {
      // 区号显示
     const areaArr = this.$store.state.user.dictionary.areaCodeList;
     areaArr.map(( sub: any ) => {
        sub.show = sub.areaName + ' +' + sub.areaCode;
     });
     this.areaCodeList = areaArr;
     if (this.id !== '-1') {
       this.getDetail();
    }
  }
  public created() {
    // this.getCvsList();
  }
  // 验证密码
  public validatePass(rule: object, value: string, callback: (obj ?: object) => void) {
    if (value === '') {
      callback(new Error('请输入密码'));
    } else {
      if (this.form.accountPasswd2 !== '') {
        this.$refs.form.validateField('accountPasswd2');
      }
      callback();
    }
  }
  // 验证确定密码
  public validatePass2(rule: object, value: string, callback: (obj ?: object) => void) {
    if (value === '') {
      callback(new Error('请再次输入密码'));
    } else if (value !== this.form.accountPasswd) {
      callback(new Error('两次输入密码不一致!'));
    } else {
      callback();
    }
  }
  // 验证电话
  public validatePhone(rule: object, value: string, callback: (obj ?: object) => void) {
      // if (value === '' || value === null) {
      //     callback(new Error('请输入移动电话'));
      // } else {
      //     if (!(/^1(3|4|5|7|8)\d{9}$/.test(value))) {
      //         callback(new Error('移动电话输入有误'));
      //     } else {
      //         callback();
      //     }
      // }
      if (value && !(/^1(3|4|5|7|8)\d{9}$/.test(value))) {
          callback(new Error('移动电话输入有误'));
      } else {
           callback();
      }
  }
  // 验证ip
  public validateIp(rule: object, value: string, callback: (obj ?: object) => void) {
        if (value === '' || value === null) {
            callback(new Error('请输入ip'));
        } else {
            if (!(/^[\d+,-]+/.test(value))) {
                callback(new Error('请输入正确的ip'));
            } else {
                callback();
            }
        }
  }
  // 用户类型改变
  public changeUserType(val: string) {
       if (val === '1') { // 公司
          this.rules.userName = [
              { min: 1, max: 20, message: '20个字符以内', trigger: 'blur' }
          ];
      } else  if (val === '2') { // 个人
          this.form.company = '';
          this.rules.userName = [
              { required: true, message: '请输入用户名称', trigger: 'blur' },
              { min: 1, max: 20, message: '20个字符以内', trigger: 'blur' }
          ];
      }  else if (val === '3') { // 高校
          this.form.company = '';
          this.rules.userName = [
               { required: true, message: '请输入高校名称', trigger: 'blur' },
              { min: 1, max: 20, message: '20个字符以内', trigger: 'blur' }
          ];
      }
  }
  // 区号显示效果
  public showOption(val: boolean) { //是否显示下拉
     this.isOptionShow = val;
  }
  // 检验字段方法
  public validationField(formName: string) {
     this.$refs[formName].validate((valid) => {
          if (valid) {
            this.addCvsUser();
          } else {
            return;
          }
      });
  }
  // 重置表单
  public resetForm(formName: string) {
    this.$refs[formName].resetFields();
  }
  public async addCvsUser() {
      delete this.form.accountPasswd2;
      const params: CvsUserDTO = JSON.parse(JSON.stringify(this.form));
      //数据处理
      let str = '';
      this.ipArr.map(( item: any, index: number ) => {
        str += item.ip + ( index < this.ipArr.length - 1 ? ',' : '') ;
      });
      params.ipLimit = str;
      // 新建
      if (this.id === '-1') {
        params.licenseStartDate = '';
        params.modifierId = '';
        params.lastLoginTime = '';
        params.modifyTime = new Date().getTime() + '';
     
        params.createTime = new Date().getTime() + '';
        params.createrId = this.logoId;

        params.id = '';
        // params.status = this.status;
        const res = await CvsUserService.saveUser(params);
        if (res.resCode === '0') {
            //   this.$message({
            //       message: '添加cvs用户成功！',
            //       type: 'success',
            //       center: true
            //   });
            //   this.isShowAddFun(); // 关闭dialog
            this.$emit('getCvsList'); //重新获取列表数据
            this.$confirm('已保存至cvs列表', '保存成功', {
                confirmButtonText: '继续操作',
                cancelButtonText: '返回列表页',
                type: 'success'
            }).then(() => {
                this.resetForm('form'); // 重置表单 
                this.changePwdFlag = false;
            }).catch(() => {
                this.isShowAddFun(); // 关闭弹框     
            });
        }
      } else { // 编辑
        // const cvsUserParams = { cvsUserDTO: params};
        if ( params.accountPasswd === '******' ) {
            params.accountPasswd = '';
        }
        const res = await CvsUserService.updateUser( params );
        // console.log(res, 'ppppp');
        if (res.resCode === '0') {
            // this.$message({
            //     message: '修改cvs用户成功！',
            //     type: 'success',
            //     center: true
            // });
            // this.isShowAddFun(); // 关闭dialog
             this.$emit('getCvsList'); //重新获取列表数据
             this.$confirm('已保存至用户列表', '保存成功', {
                    confirmButtonText: '继续操作',
                    cancelButtonText: '返回列表页',
                    type: 'success'
                }).then(() => {
                    this.getDetail();
                    this.changePwdFlag = false;
                }).catch(() => {
                    this.isShowAddFun(); // 关闭弹框     
                });
        }
      }
  }
  //获取用户详情
  public async getDetail() {
      const res = await CvsUserService.getUserById( this.id );
      const data = Object.assign( res );
      data.userType = data.userType + '';
      this.changeUserType( data.userType ); // 改变用户类型
      data.licenseStatus = data.licenseStatus + '';
      data.accountPasswd = '******';
      data.accountPasswd2 = '******';
      this.form = data; // 数据
      // ip显示处理
      if (this.form.ipLimit) {
        const str = this.form.ipLimit;
        const arr = str.split(',');
        arr.map((item: string, index: number) => {
            this.ipArr[index] = {ip: item};
        });
      }
  }
    // 进入修改密码状态
  public changePassConfirm() {
      if (!this.changePwdFlag) {
          this.$confirm('是否重置密码?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
          }).then(() => {
              //清空密码
              this.form.accountPasswd = '';
              this.form.accountPasswd2 = '';
              this.changePwdFlag = true;
          }).catch(() => {
              return;
          });
      }
  }
   // 添加一行
  public addRow() {
    this.ipArr.push({ip: '' });
  }
  // 删除一行
  public removeRow(index: number) {
    this.ipArr.splice(index, 1);
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>

</style>
